﻿using System;
using Microsoft.SharePoint;
using System.Net;
using System.Xml.Linq;
using System.Linq;
using System.Xml;
using System.Collections.Generic;

namespace CodeCounsel.StateReports
{
    class ReportDataManager
    {
        static XNamespace XMLNS_Atom = "http://www.w3.org/2005/Atom";
        static XNamespace XMLNS_ExcelRest = "http://schemas.microsoft.com/office/2008/07/excelservices/rest";

        public SPWeb Site { get; private set; }
        public string WorkbookUrl { get; private set; }
        public string RESTUrl { get; private set; }
        public WebClient Client { get; private set; }

        public ReportDataManager(SPWeb site, string workbookUrl)
        {
            Site = site;
            WorkbookUrl = site.ServerRelativeUrl + workbookUrl;
            Client = new WebClient();
            Client.UseDefaultCredentials = true;
            RESTUrl = Site.Url + "/_vti_bin/ExcelRest.aspx";
        }

        public string GetStateReportTitle(string state)
        {
            XDocument stateTitle = RunQuery("/model/Ranges('Title')?$format=atom&Ranges('State')=" + state);
            return stateTitle.Descendants(XMLNS_ExcelRest + "c").First().Value.Trim();
        }

        public byte[] GetStateReport(string state)
        {
            return Client.DownloadData(RESTUrl + WorkbookUrl + "/model/Charts('Report')?Ranges('State')=" + state);
        }

        public IEnumerable<string> GetStates()
        {
            XDocument states = RunQuery("/model/Ranges('States')?$format=atom");
            foreach (XElement state in states.Descendants(XMLNS_ExcelRest + "c"))
            {
                yield return state.Value.Trim();
            }
        }

        XDocument RunQuery(string query)
        {
            XDocument document = null;
            SPSecurity.RunWithElevatedPrivileges(
                delegate
                {
                    try
                    {
                        using (XmlReader reader = XmlReader.Create(
                            Client.OpenRead(RESTUrl + WorkbookUrl + query)))
                        {
                            document = XDocument.Load(reader);
                        }
                    }
                    catch (WebException)
                    {
                        throw;
                    }
                    catch (TimeoutException)
                    {
                        throw;
                    }
                });
            return document;
        }
    }
}
